// 图形验证码相关
export default (props?: any) => {
  const identifyCodes = ref('1234567890abcdefghizklmnopqrstuvwxyz')
  const identifyCode = ref('')
  // 生成一个随机数
  const randomNum = (min: number, max: number) => Math.floor(Math.random() * (max - min) + min)

  // 生成一个随机的颜色
  const randomColor = (min: number, max: number) => {
    const r = randomNum(min, max),
      g = randomNum(min, max),
      b = randomNum(min, max)
    return 'rgb(' + r + ',' + g + ',' + b + ')'
  }

  // 绘制
  const drawPic = () => {
    let canvas = document.getElementById('s-canvas')
    let ctx = (canvas as HTMLCanvasElement).getContext('2d')
    if (!ctx) return
    ctx.textBaseline = 'bottom'
    // 绘制背景
    ctx.fillStyle = randomColor(props.backgroundColorMin, props.backgroundColorMax)
    ctx.fillRect(0, 0, props.contentWidth, props.contentHeight)
    // 绘制文字
    for (let i = 0; i < props.identifyCode.length; i++) {
      drawText(ctx, props.identifyCode[i], i)
    }
    //去掉绘制干扰点和干扰线
    drawLine(ctx)
    drawDot(ctx)
  }

  const drawText = (ctx: CanvasRenderingContext2D, txt: string, i: number) => {
    // console.log("绘制", txt);
    ctx.fillStyle = randomColor(props.colorMin, props.colorMax)
    ctx.font = /* this.randomNum(this.fontSizeMin, this.fontSizeMax) + */ '35px SimHei'
    let x = (i + 1) * (props.contentWidth / (props.identifyCode.length + 1))
    let y = randomNum(props.fontSizeMax, props.contentHeight - 5)
    var deg = randomNum(-15, 15)
    // 修改坐标原点和旋转角度
    ctx.translate(x, y)
    ctx.rotate((deg * Math.PI) / 180)
    ctx.fillText(txt, 0, 0)
    // 恢复坐标原点和旋转角度
    ctx.rotate((-deg * Math.PI) / 180)
    ctx.translate(-x, -y)
  }

  // 绘制干扰线
  const drawLine = (ctx: CanvasRenderingContext2D) => {
    for (let i = 0; i < 3; i++) {
      ctx.strokeStyle = randomColor(props.lineColorMin, props.lineColorMax)
      ctx.beginPath()
      ctx.moveTo(randomNum(0, props.contentWidth), randomNum(0, props.contentHeight))
      ctx.lineTo(randomNum(0, props.contentWidth), randomNum(0, props.contentHeight))
      ctx.stroke()
    }
  }

  // 绘制干扰点
  const drawDot = (ctx: CanvasRenderingContext2D) => {
    return
    for (let i = 0; i < 100; i++) {
      ctx.fillStyle = randomColor(0, 255)
      ctx.beginPath()
      ctx.arc(randomNum(0, props.contentWidth), randomNum(0, props.contentHeight), 1, 0, 2 * Math.PI)
      ctx.fill()
    }
  }

  // 刷新验证码
  const refreshCode = (len = 4) => {
    identifyCode.value = ''
    for (let i = 0; i < len; i++) {
      identifyCode.value += identifyCodes.value[randomNum(0, identifyCodes.value.length)]
    }
    // console.log(identifyCode.value);
  }

  return {
    refreshCode,
    identifyCodes,
    identifyCode,
    drawDot,
    drawLine,
    drawPic,
    drawText,
    randomColor,
    randomNum,
  }
}
